/**业务管理流程平台版本1.0,生成时间:2017-04-13 13:16:48**/
package com.xbdun.service.bmp.service.system.impl;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbdun.common.api.Client;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.dao.bmp.entity.XbdunSysOrgFiledsDo;
import com.xbdun.dao.bmp.mapper.SysOrgFiledsMapper;
import com.xbdun.facade.bmp.request.system.SysOrgFiledsRequest;
import com.xbdun.facade.bmp.response.system.SysOrgFiledsResponse;
import com.xbdun.service.bmp.service.cache.OrgInfoCacheService;
import com.xbdun.service.bmp.service.system.SysOrgFiledsService;

/**
 * @ClassName: SysOrgFiledsServiceImpl
 * @Description: 机构附属信息
 * @category 机构附属信息
 * @author wwq@xbdun.com
 * @date 2017年6月16日 下午3:56:10
 */
@Service
@Transactional
public class SysOrgFiledsServiceImpl implements SysOrgFiledsService {
	@Autowired
	private SysOrgFiledsMapper sysOrgFiledsMapper;
	@Autowired
	OrgInfoCacheService orgInfoCacheService;
	
	public SysOrgFiledsResponse getSysOrgFiledsByOrgCode(long orgCode)throws Exception{
		if (orgCode <= 0 ) throw BizException.PARAM_CHKE_FAIL.newInstance("机构orgCode不能小于等于零");
		XbdunSysOrgFiledsDo filedsDo = sysOrgFiledsMapper.getSysOrgFiledsByOrgCode(orgCode);
		if ( null == filedsDo) {
			return null;
		}
		// 资源Copy
		SysOrgFiledsResponse response = new SysOrgFiledsResponse();
		BeanUtils.copyProperties(response, filedsDo);
		return response;
	}

	public void modifySysOrgFileds(SysOrgFiledsRequest request,Client client)throws Exception{
		XbdunSysOrgFiledsDo fdo = new XbdunSysOrgFiledsDo();
		BeanUtils.copyProperties(fdo, request);
		fdo.setOrgCode(client.getOrgCode());
		
		XbdunSysOrgFiledsDo filedsDo = sysOrgFiledsMapper.getSysOrgFiledsByOrgCode(client.getOrgCode());
		if(null == filedsDo) {
			//如果不存在初始化机构附属信息
			addSysOrgFileds(request, client);
		}else{
			if(0==sysOrgFiledsMapper.modifySysOrgFileds(fdo)){
				throw BizException.DB_UPDATE_RESULT_0.newInstance("更新机构附属信息失败");
			}
			//删除缓存机构附加信息
			orgInfoCacheService.removeOrgFildes(fdo.getOrgCode());
		}
	}

	public void addSysOrgFileds(SysOrgFiledsRequest request, Client client) throws Exception {
		XbdunSysOrgFiledsDo fdo = new XbdunSysOrgFiledsDo();
		BeanUtils.copyProperties(fdo, request);
		fdo.setOrgCode(client.getOrgCode());
		if(0==sysOrgFiledsMapper.addSysOrgFileds(fdo)){
			throw BizException.DB_INSERT_RESULT_0.newInstance("新增机构附属信息失败");
		}
	}
}